<#include "../../layout/mainLayout.ftl">
<@layout>

    <div class="layui-card">
        <div class="layui-card-header">
            <span class="layui-breadcrumb">
                ${breadcrumb!''}
            </span>
        </div>
    </div>
    <div class="layui-card">
        <div class="layui-card-body"> 
        	<form class="layui-form" id="queryForm">
        		 <div class="layui-form-item"> 
        		 	<!-- <label class="layui-form-label" style="width: auto">填报单位</label>
                    <div class="layui-input-inline">
                        <input type="text" name="reportingUnit" class="layui-input" placeholder="填报单位关键字模糊搜索" style="width:auto">
                    </div>     -->      
                    <div>
                    	<!-- <button type="button" class="layui-btn" lay-submit="" id="queryPage">查询</button> -->                  
						<button type="button" class="layui-btn" id="exportTable">导出本页表格</button>                    
						<button type="button" class="layui-btn" id="exportAllTable">导出全部表格</button>
					</div>									                                  
    			</div>
              
            </form>
           <div class="table-responsive table2excel" data-tableName="Test Table 1">         
			<table id="tableid"  class="layui-table" lay-data="{ url:'/tMatter/pageJSONData', page: true, size: 10,}">
			  <thead>
			    <tr>
			      <th lay-data="{checkbox:true, fixed:'left'}" rowspan="2"></th>
			      <th lay-data="{field:'subordinateSystem', width:100, align: 'center'}" rowspan="2">所属系统</th>
			      <th lay-data="{field:'matterName', width:150, align: 'center'}" rowspan="2">办理事项名称</th>
			      <th lay-data="{field:'matterAttr', width:100, align: 'center', templet: function(d){
                    	if(d.matterAttr == 1){
                    		return '公共服务'
                    	} else if(d.matterAttr == 2){
                    		return '权力事项'
                    	}
                      }}" rowspan="2" >事项属性</th>
			      <th lay-data="{field:'handleDeptLevel', width:150, align: 'center'}" rowspan="2">可办理部门层级</th>  
			      <th lay-data="{field:'wayCommunityHandle', width:300, align: 'center', templet: function(d){
                    	if(d.wayCommunityHandle == 1){
                    		return '直接办理'
                    	} else if(d.wayCommunityHandle == 2){
                    		return '委托办理'
                    	} else if(d.wayCommunityHandle == '' ){
                    		return ''
                    	} else if(d.wayCommunityHandle == null ){
                    		return ''
                    	}
                      }}" rowspan="2">在社区办理：注明直接办理、委托办理</th>
			      <th lay-data="{field:'personCount', width:250, align: 'center'}" rowspan="2">当前需要相对人到现场的次数</th>
			      <th lay-data="{field:'onceFlag', width:300, align: 'center', templet: function(d){
                    	if(d.onceFlag == 1){
                    		return '是'
                    	} else if(d.onceFlag == 2){
                    		return '否'
                    	} else if(d.onceFlag == null){
                    		return ''
                    	}
                      }}" rowspan="2">是否可以“实现最多跑一次”</th>
			      <th lay-data="{align:'center', align: 'center'}" colspan="3">办事所需材料</th>
			      <th lay-data="{field:'onlineHandleChannels', width:300, align: 'center'}" rowspan="2">注明网址、手机app渠道名称</th>
			      <th lay-data="{field:'selfServiceFlag', width:200, align: 'center', templet: function(d){
                    	if(d.selfServiceFlag == 1){
                    		if(d.selfServiceAddr == null){
                    			return '是;'
                    		}
                    		return '是'+';'+d.selfServiceAddr
                    	}  else if(d.selfServiceFlag == 2){
                    		return '否'
                    	} else if(d.selfServiceFlag == null){
                    		return ''
                    	}
                      }}" rowspan="2">是否有自助端，配置点地址</th>
			      <th lay-data="{field:'bizConsultingWebFlag', width:150, align: 'center', templet: function(d){
                    	if(d.bizConsultingWebFlag == 1){
                    		if(d.bizConsultingWebAddr == null){
                    			return '是'+';'
                    		}
                    		return '是'+';'+d.bizConsultingWebAddr
                    	} else if(d.bizConsultingWebFlag == 2){
                    		return '否'
                    	} else if(d.bizConsultingWebFlag == null){
                    		return ''
                    	}
                      }}" rowspan="2">是否有业务咨询网站：若有请注明网址</th>
			      <th lay-data="{field:'bringHotlineFlag', width:400, align: 'center', templet: function(d){
                    	if(d.bringHotlineFlag == 1){
                    		return '是'
                    	} else if(d.bringHotlineFlag == 2){
                    		return '否'+';'+d.bizConsultingHotline
                    	} else if(d.bringHotlineFlag == null){
                    		return ''
                    	}
                      }}" rowspan="2">业务咨询电话是否归入12345：若否请注明电话</th>
			      <th lay-data="{align:'center', align: 'center'}" colspan="2">仅需身份证或市民卡办理情况</th>
			      <th lay-data="{align:'center', align: 'center'}" colspan="2">证明材料精简建议</th>
			      <th lay-data="{field:'remarks', width:200, align: 'center'}" rowspan="2">备注</th>			      
			    </tr>
			    <tr>
			      <th lay-data="{field:'idcardFlag', width:200, align: 'center', templet: function(d){
                    	if(d.idcardFlag == 1){
                    		return '已可'
                    	} else if(d.idcardFlag == 2){
                    		return '拟可'
                    	} else if(d.idcardFlag == 3){
                    		return '不可'
                    	}
                      }}">是否仅需身份证或市民卡就可办理</th>
			      <th lay-data="{field:'materialsListLocal', width:200, align: 'center'}">本地市民需要材料清单</th>
			      <th lay-data="{field:'materialsListOutside', width:200, align: 'center'}">非本地市民需要材料清单</th>
			      <th lay-data="{field:'fieldIdcardFlagNow', width:200, align: 'center', templet: function(d){
                    	if(d.fieldIdcardFlagNow == 1){
                    		return '是'
                    	} else if(d.fieldIdcardFlagNow == 2){
                    		return '否'
                    	} else if(d.fieldIdcardFlagNow == null){
                    		return ''
                    	}
                      }}">是否仅需身份证或市民卡就可办理</th>
			      <th lay-data="{field:'changeMeasure', width:200, align: 'center'}">主要改革措施</th>
			      <th lay-data="{field:'cancelMaterialsList', width:200, align: 'center'}">取消(共享)证明材料名称</th>
			      <th lay-data="{field:'materialsDeptList', width:200, align: 'center'}">证明材料信息涉及提供部门</th>	     
			    </tr>
			  </thead>
			</table>
		  </div>	
        </div>
    </div>
</@layout>
<@js>
    <script>  
      	layui.config({
			base: '/static/module/'
			}).use(['laydate', 'table', 'layer', 'global','excel'], function () {
            var table = layui.table, layer = layui.layer, $ = layui.$, laydate = layui.laydate,excel = layui.excel;
           
           	  //点我导出表格
		    $("#exportTable").on('click',function(){
		    	exportFile('tableid')
		    });		    
            
            //搜索
            $('#queryPage').click(function () {
                reloadTable(true);
            });
            
            window.reloadTable = function (reset = false) {
                var fields = {};
                $.each($('#queryForm').serializeArray(), function (i, field) {
                    fields[field.name] = field.value;
                });
                tableid.reload({
                    where: fields,
                    page: reset?{
                        curr: 1 //重新从第 1 页开始
                    }:undefined
                });
            };
		    
		   //获取传输数据
		    $('#exportAllTable').click(function () {
                $.ajax({                	
                    url: '/tMatter/pageExcel',
                    async: false,
                    success: function (data, status, xhr) {
                        exportAll('tableid',data)
                    }
                });
            });
            
            //------------------导出本页数据-----------------------------
		    function exportFile(id) {
				//根据传入tableID获取表头
				var headers = $("div[lay-id=" + id + "] .layui-table-box table").get(0);
				var htrs = Array.from(headers.querySelectorAll('tr'));				
				var titles = [],htrSlice = []
				for (var j = 0; j < htrs.length; j++) {
					//每一列的表头
					var hths = Array.from(htrs[j].querySelectorAll("th"));
					if(hths.length>0){
						titles[j] = {},htrSlice[j] = []
						var _thisRow = titles[j]
						for (var i = 0; i < hths.length; i++) {
							//得到跨列解释表头
							var clazz = hths[i].getAttributeNode('class').value;
							if (((clazz == ' layui-table-col-special'&&i>0)||(clazz != ' layui-table-col-special')) && clazz != 'layui-hide') {
								//排除居左、具有、隐藏字段
								//修改:默认字段data-field+i,兼容部分数据表格中不存在data-field值的问题
								var index = Object.keys(_thisRow).length+1
								//获取表头的值
								_thisRow['data-field' + index] = hths[i].innerText;
								if(hths[i].colSpan>1){
									htrSlice[j].push({colSpan:hths[i].colSpan,index:index})
									for(var k =1;k<hths[i].colSpan;k++){
										_thisRow['data-field' + (index+k)] = '';
									}
								}
							}
						}
					} 
				}
				if(htrSlice[0].length>0){
					// _newhtr 复制第一行表头合并数据 _newTitle 复制第二行表头数据 _newTitle1 复制第一行表头数据 index 总列数
					var _newTitle = $.extend({},titles[1]),_newTitle1 = $.extend({},titles[0]),_newhtr = $.extend([],htrSlice[0]),index = Object.keys(titles[0]).length,row ={}
					// 初始生成全部列
					for(var i=1;i<=index;i++){
						row['data-field' + i] = '';
					}
					// colSpan 跨列数 index 从第几列开始
					for(var j=0;j<_newhtr.length;j++){
						for(var z=0;z<_newhtr[j].colSpan;z++){
							// 更新所跨列数据
							row['data-field' + (_newhtr[j].index+z)] = _newTitle[Object.keys(_newTitle)[0]]
							//_newTitle.splice(0,1)
							// 删除_newTitle第一个数据
							delete _newTitle[Object.keys(_newTitle)[0]]; 
						}
					}
					/* for(var j=0;j<_newhtr.length;j++){
						var num = j<1 ? 1 : _newhtr[j-1].index+_newhtr[j-1].colSpan
						for(var z=num;z<_newhtr[j].index;z++){
							row['data-field' + z] = _newTitle1['data-field' + z]
							titles[0]['data-field' + z] = ''
						}
					} */
					titles[1] = row
				}
				//根据传入tableID获取table内容
				var bodys = $("div[lay-id=" + id + "] .layui-table-box table").get(1);				
				var btrs = Array.from(bodys.querySelectorAll("tr"))
				var bodysArr = new Array();
				for (var j = 0; j < btrs.length; j++) {
					var contents = {};
					var btds = Array.from(btrs[j].querySelectorAll("td"));					
					for (var i = 0; i < btds.length; i++) {
						for (var key in titles[0]) {
							//修改:默认字段data-field+i,兼容部分数据表格中不存在data-field值的问题
							var field = 'data-field' + i;
							if (field === key) {
								//根据表头字段获取table内容字段
								contents[field] = btds[i].innerText;
							}
						}
					}
					bodysArr.push(contents)
				}
				//将标题行置顶添加到数组
				for(var z = titles.length-1;z>=0;z--){
					bodysArr.unshift(titles[z]);
				}
				//bodysArr.unshift(titles);
				 var mergeConf = excel.makeMergeConfig([
			      ['H1', 'J1'],
			      ['O1', 'P1'],
			      ['Q1', 'R1'],
			      ['A1', 'A2'],
			      ['B1', 'B2'],
			      ['C1', 'C2'],
			      ['D1', 'D2'],
			      ['E1', 'E2'],
			      ['F1', 'F2'],
			      ['G1', 'G2'],
			      ['K1', 'K2'],
			      ['L1', 'L2'],
			      ['M1', 'M2'],
			      ['N1', 'N2'],
			      ['S1', 'S2'],
			    ])
			    var colConf = excel.makeColConfig({
			    	'A': 100,
      				'Z': 100
			    },100)
				//导出excel
				excel.exportExcel({
					sheet1: bodysArr
				}, '用户表' + new Date().toLocaleString() + '.xlsx', 'xlsx',{
					extend: {
				        // extend 中可以指定某个 sheet 的属性，如果不指定 sheet 则所有 sheet 套用同一套属性
				          '!merges': mergeConf,
				          '!cols': colConf
				      }
				});
			}
		    
		    //---------------------导出数据库全部数据（排除删除数据（影藏数据））----------------------------
		    function exportAll(id,data) {
				//根据传入tableID获取表头
				var headers = $("div[lay-id=" + id + "] .layui-table-box table").get(0);
				var htrs = Array.from(headers.querySelectorAll('tr'));
				var titles = [],htrSlice = []
				for (var j = 0; j < htrs.length; j++) {
					var hths = Array.from(htrs[j].querySelectorAll("th"));
					if(hths.length>0){
						titles[j] = {},htrSlice[j] = []
						var _thisRow = titles[j]
						for (var i = 0; i < hths.length; i++) {
							var clazz = hths[i].getAttributeNode('class').value;
							//if (clazz != ' layui-table-col-special' && clazz != 'layui-hide') {
							if (((clazz == ' layui-table-col-special'&&i>0)||(clazz != ' layui-table-col-special')) && clazz != 'layui-hide') {
								//排除居左、具有、隐藏字段
								//修改:默认字段data-field+i,兼容部分数据表格中不存在data-field值的问题
								//titles['data-field' + i] = hths[i].innerText;
								var index = Object.keys(_thisRow).length+1
								_thisRow['data-field' + index] = hths[i].innerText;
								if(hths[i].colSpan>1){
									htrSlice[j].push({colSpan:hths[i].colSpan,index:index})
									for(var k =1;k<hths[i].colSpan;k++){
										_thisRow['data-field' + (index+k)] = '';
									}
								}
							}
						}
					} 
				}
				if(htrSlice[0].length>0){
					var _newTitle = $.extend({},titles[1]),_newhtr = $.extend([],htrSlice[0]),index = Object.keys(titles[0]).length,row ={}
					for(var i=1;i<=index;i++){
						row['data-field' + i] = '';
					}
					for(var j=0;j<_newhtr.length;j++){
						for(var z=0;z<_newhtr[j].colSpan;z++){
							row['data-field' + (_newhtr[j].index+z)] = _newTitle[Object.keys(_newTitle)[0]]
							//_newTitle.splice(0,1)
							delete _newTitle[Object.keys(_newTitle)[0]]; 
						}
					}
					titles[1] = row
				}

				//根据传入tableID获取table内容
				var bodys = $("div[lay-id=" + id + "] .layui-table-box table").get(1);	
				var cc = JSON.parse(data);				
				var bodysArr = new Array();				
				for (var j = 0; j <  cc.data.length; j++) {
					var contents = {};
					var btds = cc.data[j];					
					contents["data-field1"] = btds.subordinateSystem;//所属系统
					contents["data-field2"] = btds.matterName;//办理事项名称
					contents["data-field3"] = btds.matterAttr;//事项属性
					contents["data-field4"] = btds.handleDeptLevel;//可办理部门层级
					contents["data-field5"] = btds.wayCommunityHandle;//在社区办理
					contents["data-field6"] = btds.personCount;//当前需要相对人到现场的次数
					contents["data-field7"] = btds.onceFlag;//是否可以“实现最多跑一次”
					contents["data-field8"] = btds.idcardFlag;//是否仅需身份证或市民卡就可办理
					contents["data-field9"] = btds.materialsListLocal;//本地市民需要材料清单
					contents["data-field10"] = btds.materialsListOutside;//非本地市民需要材料清单
					contents["data-field11"] = btds.onlineHandleChannels;//注明网址、手机app渠道名称
					contents["data-field12"] = btds.selfServiceFlag;//是否有自助端，配置点地址
					contents["data-field13"] = btds.bizConsultingWebFlag;//是否有业务咨询网站：若有请注明网址
					contents["data-field14"] = btds.bringHotlineFlag;//业务咨询电话是否归入12345：若否请注明电话
					contents["data-field15"] = btds.fieldIdcardFlagNow;//是否仅需身份证或市民卡就可办理
					contents["data-field16"] = btds.changeMeasure;//主要改革措施
					contents["data-field17"] = btds.cancelMaterialsList;//取消(共享)证明材料名称
					contents["data-field18"] = btds.materialsDeptList;//证明材料信息涉及提供部门
					contents["data-field19"] = btds.remarks;//备注					
					bodysArr.push(contents)
				}
				//将标题行置顶添加到数组
				for(var z = titles.length-1;z>=0;z--){
					bodysArr.unshift(titles[z]);
				}
				//bodysArr.unshift(titles);
				 var mergeConf = excel.makeMergeConfig([
					['H1', 'J1'],
					['O1', 'P1'],
					['Q1', 'R1'],
					['A1', 'A2'],
					['B1', 'B2'],
					['C1', 'C2'],
					['D1', 'D2'],
					['E1', 'E2'],
					['F1', 'F2'],
					['G1', 'G2'],
					['K1', 'K2'],
					['L1', 'L2'],
					['M1', 'M2'],
					['N1', 'N2'],
					['S1', 'S2'],
			    ])
			    var colConf = excel.makeColConfig({
			    	'A': 100,
      				'Z': 100
			    },100)
				//导出excel
				excel.exportExcel({
					sheet1: bodysArr
				}, '用户表' + new Date().toLocaleString() + '.xlsx', 'xlsx',{
					extend: {
				        // extend 中可以指定某个 sheet 的属性，如果不指定 sheet 则所有 sheet 套用同一套属性
				          '!merges': mergeConf,
				          '!cols': colConf
				      }
				});
			}
        });               
    </script>
</@js>